<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
defineOptions({
  name: 'bubble-container'
})
const props = defineProps({
  message: {
    type: String,
    default: ''
  },
  isDialogShow: {
    type: Boolean,
    default: true
  },
  isFading: {
    // 是否淡出
    type: Boolean,
    default: true
  },
  leftFixedPx: {
    type: Number,
    default: 0
  }
})
const dialogRef = ref()
const getWidth = () => {
  return dialogRef.value?.getBoundingClientRect().width
}
const setDialogRightMove = () => {
  dialogRef.value.style.left = `-${getWidth() + 20 + props.leftFixedPx}px`
}

onMounted(() => {
  if (!props.isDialogShow) return
  setDialogRightMove()
  typeWriter()
})
const message = ref('')
// 打字机效果
const typeWriter = () => {
  let index = 0
  const timer = setInterval(() => {
    if (index < props.message.length) {
      message.value = props.message.slice(0, index + 1)
      index++
      setDialogRightMove()
    } else {
      watch(message, () => {
        setDialogRightMove()
      })
      clearInterval(timer)
      props.isFading &&
        setTimeout(() => {
          dialogRef.value.style.opacity = '0'
        }, 5000)
    }
  }, 100)
}
</script>

<template>
  <!-- 对话气泡框 -->
  <section class="dialog" ref="dialogRef" v-if="props.isDialogShow">
    {{ message }}
  </section>
</template>

<style lang="scss" scoped>
.dialog {
  position: absolute;
  max-width: 300px;
  padding: 20px;
  background-color: #67c23a;
  // opacity: 0.5;
  border-radius: 10px;
  color: #fff;
  left: -20px;
  top: 30%;
  font-size: 25px;
  transition: opacity 1s;
  // 为气泡框加一个向右的小三角
  &::before {
    content: '';
    position: absolute;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #67c23a;
    right: -8px;
    top: 10px;
  }
}
</style>
